package com.flyweight;

import java.util.Hashtable;
import com.flyweight.face.Flyweight;
import com.flyweight.impl.ConcreateFlyweight;

/**
 * 创建Flyweight的工厂类，创建后将其保存到Flyweight Pool中
 * 
 * @author dell
 * 
 */
public class FlyweightFactory {

	private static FlyweightFactory instance;

	private FlyweightFactory() {

	}

	public static synchronized FlyweightFactory getInstance() {
		if (instance == null) {
			instance = new FlyweightFactory();
		}
		return instance;
	}

	// 缓冲Flyweight对象的池，通常包含在工厂类中
	private Hashtable<Object, Flyweight> flyweights = new Hashtable<Object, Flyweight>();

	public Flyweight getFlyweight(Object key) {
		Flyweight flyweight = null;
		if (flyweights.containsKey(key)) {
			flyweight = flyweights.get(key);
		}
		if (!flyweights.containsKey(key)) {
			flyweight = new ConcreateFlyweight(key);
			flyweights.put(key, flyweight);
		}
		return flyweight;
	}

	public int getFlyweightsSize() {
		return flyweights.size();
	}

}
